package cn.itheima.taotao.controller;

import cn.itheima.taotao.utils.FastDFSClient;
import cn.itheima.taotao.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator .
 */
@Controller
public class PictureController {
    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

    @RequestMapping(value = "/pic/upload", produces = MediaType.TEXT_PLAIN_VALUE + ";chartset=utf-8")
    @ResponseBody
    public String fileUpload(MultipartFile uploadFile) {
        String originalFilename = uploadFile.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        Map map = new HashMap();
        try {
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:resources/client.conf");
            String path = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
            map.put("error",0);
            map.put("url",IMAGE_SERVER_URL+path);
            return JsonUtils.objectToJson(map);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("error",1);
            map.put("message","图片上传失败!");
            return JsonUtils.objectToJson(map);
        }
    }
}
